import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from aws_model.athena_submit import submit
from config import hour_bucket
from sql_lambda.delete import delete
from base_class.inspect_logging import print_to_log
import datetime
import json
from aws_model.aws_stepfunc import send_task_success, send_task_failure


def ac_online_device(event):
    date = event.get('p_date')
    if not date:
        beijing = datetime.timezone(datetime.timedelta(hours=7))
        date = datetime.datetime.now(tz=beijing).strftime('%Y-%m-%d-%H')
    delete(hour_bucket,f'ads/ac_online_device/p_date={date}')
    filter_date = date[0:10]
    filter_hour = date[11:13]
    table_name = sys._getframe().f_code.co_name
    sql = f'''insert into ads.ac_online_device
                    (
                    select
                        t.inner_sn,
                        t.outer_sn ,
                        t.model,
                        TRY(substr(t.inner_sn,11,2)) as inner_version,
                        TRY(substr(t.outer_sn,11,2)) as outer_version,
                        t.last_report_time,
                        t.city,
                        t.province,
                        t.region,
                        t.open,
                        '{date}' as p_date
                    from
                         (
                        select
                            t.sn as inner_sn,
                            b.outer_sn as outer_sn,
                            if(b.model is null,t.model,b.model) as model,
                            t.last_report_time,
                            b.region,
                            b.city,
                            b.province,
                            if(open>0,1,0) open
                        from
                            (select
                                sn,
                                model,
                                max(timestamp) as last_report_time,
                                sum(if(open = true,1,0)) as open
                            from
                                ods.iot_ac t
                            where
                                p_date = '{filter_date}'
                            and
                                substr(timestamp,1,13) = '{filter_date} {filter_hour}'
                            group by
                                sn,model
                            UNION
                             select
                                sn,
                                model,
                                max(timestamp) as last_report_time,
                                sum(if(power = '1',1,0)) as open
                            from
                                ods.iot_ac_mqtt t
                            where
                                p_date = '{filter_date}'
                            and
                                substr(timestamp,1,13) = '{filter_date} {filter_hour}'
                            group by
                                sn,model
                            ) t
                        join
                            (select inner_sn,outer_sn,region,province,city,model from dws.ac_all_device_life_td) as b
                        on
                            t.sn = b.inner_sn
                        ) t
                    )'''
    athena_response = submit(sql)
    print_to_log("athena_response: ", athena_response)
    output = {"msg": f"{table_name} submit ok", "Payload": {}}
    output = json.dumps(output)
    step_response = send_task_success(tasktoken, output)
    print_to_log("step_response: ", step_response)


if __name__ == '__main__':
    try:
        event = json.loads(sys.argv[1])
        tasktoken = event.get('TaskToken')
        ac_online_device(event)
    except Exception as e:
        print_to_log("athena_submit 失败")
        print_to_log("原因： ", str(e))
        send_task_failure(str(e), f'执行{sys._getframe().f_code.co_filename}错误', tasktoken)
